<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-22 14:36:53
 * @FilePath: \usp-osm-frondend\src\views\serviceCenter\equityMgmt\index.vue
-->
<template>
  <div class="source" v-loading="pageLoading" element-loading-text="加载中...">
    <v-notes>
      <el-form
        label-width="160px"
        :model="serviceForm"
        ref="searchForm"
        class="search-form"
        size="small"
      >
        <el-row class="search-row">
          <el-col :span="24">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="会员名称" prop="customerName">
                  <el-input
                    placeholder="会员名称"
                    v-model="serviceForm.customerName"
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="会员手机号" prop="customerPhone">
                  <el-input
                    type="number"
                    placeholder="会员手机号"
                    v-model="serviceForm.customerPhone"
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="VIN" prop="vin">
                  <el-input
                    placeholder="VIN"
                    v-model="serviceForm.vin"
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-collapse-transition>
              <div class="filterContent" v-if="showContent">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="服务包名称" prop="servicePackageName">
                      <el-input
                        placeholder="服务包名称"
                        v-model="serviceForm.servicePackageName"
                        clearable
                        @keyup.enter.native.prevent="searchService"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="服务包编号" prop="servicePackageCode">
                      <el-input
                        placeholder="服务包编号"
                        v-model="serviceForm.servicePackageCode"
                        clearable
                        @keyup.enter.native.prevent="searchService"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="冻结状态" prop="frozenState">
                      <el-select
                        v-model="serviceForm.frozenState"
                        placeholder="请选择"
                        popper-class="select-class"
                        :popper-append-to-body="false"
                      >
                        <el-option key label="全部" value></el-option>
                        <el-option
                          v-for="item in lookupItems.FROZENSTATE"
                          :key="item.id"
                          :label="item.dicName"
                          :value="item.dicCode"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="服务绑定时间">
                      <div class="block">
                        <el-date-picker
                          v-model="serviceForm.createTime"
                          type="daterange"
                          range-separator="至"
                          :picker-options="pickerOptions"
                          :default-value="[new Date(), new Date()]"
                          value-format="yyyy-MM-dd"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                        ></el-date-picker>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-collapse-transition>
          </el-col>
        </el-row>
        <el-row class="search-row">
          <el-col :span="8" :offset="16" style="text-align: right">
            <el-button
              @click="closeFilter"
              :icon="showContent ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              class="white-btn filterClose"
            >
              {{ showContent ? '折叠' : '展开' }}
            </el-button>
            <el-button
              @click="resetForm('searchForm')"
              icon="el-icon-refresh-left"
              class="white-btn"
              >重置</el-button
            >
            <el-button
              @click="searchService"
              icon="el-icon-search"
              class="dark-btn search-btn"
              >搜索</el-button
            >
          </el-col>
        </el-row>
        <!-- Filter start -->
      </el-form>
    </v-notes>
    <div class="mb-lg">
      <v-table
        :data="tableData"
        ref="multipleTable"
        :listLoading="listLoading"
        :loadingText="loadingText"
        :paginationTotal="total"
        v-on:pageSizeChange="pageSizeChange"
        v-on:currentPageChange="currentPageChange"
        border
        pagination
        @handleSelectionChange="handleSelectionChange"
      >
        <div slot="header">
          <el-button
            @click="freeze('冻结')"
            :disabled="freezeAbled"
            class="dark-btn"
            style="margin-bottom: 0 !important"
            v-if="$auth('serviceRightsConfigurationCenter:serviceRightsManagement:freeze')"
          >
            冻结
          </el-button>
          <el-button
            @click="unfreeze('解冻')"
            :disabled="freezeAbled"
            class="dark-btn"
            style="margin-bottom: 0 !important"
            v-if="$auth('serviceRightsConfigurationCenter:serviceRightsManagement:thaw')"
          >
            解冻
          </el-button>
        </div>
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="会员ID"
          align="center"
          min-width="80"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>
              {{ scope.row.customerId }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="会员名称"
          align="center"
          min-width="140"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <!-- {{ getDictionaryNameByCode('LABELTYPE', scope.row.serviceType) }} -->
            {{ scope.row.customerName }}
          </template>
        </el-table-column>
        <el-table-column
          label="会员手机号"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.customerPhone }}
          </template>
        </el-table-column>
        <el-table-column
          label="VIN"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">{{
            scope.row.vin
          }}</template>
        </el-table-column>
        <el-table-column
          label="服务包编号"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.servicePackageCode }}
          </template>
        </el-table-column>
        <el-table-column
          label="服务包名称"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.servicePackageName }}
          </template>
        </el-table-column>
        <el-table-column
          label="冻结状态"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ getDictionaryNameByCode('FROZENSTATE', scope.row.frozenState) }}
          </template>
        </el-table-column>
        <el-table-column
          label="有效期"
          align="center"
          min-width="180px"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.beginUsePeriod | timestampToChange() }}至{{ scope.row.endUsePeriod | timestampToChange() }}
          </template>
        </el-table-column>
        <el-table-column
          prop="serviceBindTime"
          label="服务绑定时间"
          align="center"
          min-width="160px"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.serviceBindTime | timestampToChange('time') }}
          </template>
        </el-table-column>
        <el-table-column
          label="最新一次使用时间"
          align="center"
          min-width="160px"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.lastUseTime | timestampToChange('time') }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span class="colorLink" @click="toPreview(scope.row)">
              <el-tooltip class="item" effect="dark" content="详情" placement="top-start">
                <i class="el-icon-document"></i>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </v-table>
    </div>
    <!-- 冻结/解冻 -->
    <el-dialog
      :visible.sync="isFreezeDialog"
      :title="freezeTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      :element-loading-text="'加载中'"
      width="35%"
      append-to-body
      top="10px"
    >
      <div style="text-align: center; padding: 20px 0"> {{ freezeContent }} </div>
      <div class="freeze-footer">
        <el-button class="search-btn" @click="freezeSubmit(freezeTitle)">确 定</el-button>
        <el-button @click="isFreezeDialog = false" v-if="freezeShowBtn" style="margin-left: 20px"
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VNotes from '@/components/Notes/index'
import VTable from '@/components/PageTable/index'
import { getEquityList, saveServiceEdit, freezeStatus } from '@/api/service'
import { common } from '@/mixins/common'
import { mapGetters } from 'vuex'
// import { parseTime } from '@/utils'
export default {
  name: 'equityMgmt',
  components: {
    VNotes,
    VTable
  },
  mixins: [common],
  data () {
    return {
      tableData: [],
      showContent: false,
      pageLoading: false,
      isFreezeDialog: false,
      freezeAbled: true,
      freezeShowBtn: true,
      freezeTitle: '',
      freezeContent: '',
      frozenIdList: [],
      defaultTime: [new Date(), new Date()],
      statusList: [
        {
          dicCode: '1',
          dicName: '冻结'
        },
        {
          dicCode: '0',
          dicName: '正常'
        }
      ],
      serviceForm: {
        customerName: '',
        customerPhone: '',
        vin: '',
        servicePackageName: '',
        servicePackageCode: '',
        createTime: [],
        serviceProviderName: '',
        displayStart: 0, // 开始查询条数
        displayLength: 10 // 每页展示条数
      },
      selectData: [],
      listLoading: false,
      loadingText: '加载中...',
      total: 0,
      pageSize: 10,
      currentPage: 0,
      pickerOptions: {
        disabledDate (time) {
          // 如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() > Date.now() // - 8.64e7
        }
      }
    }
  },
  computed: {
    ...mapGetters(['lookupItems', 'roles'])
  },
  created () {
    this.fetchList()
  },
  mounted () {},
  methods: {
    searchService () {
      this.currentPage = 0
      this.$refs.multipleTable.restPage()
      this.fetchList()
    },
    fetchList () {
      if (
        !this.$auth('serviceRightsConfigurationCenter:serviceRightsManagement:list')
      ) {
        this.$alert('您没有权限')
        return false
      }
      this.listLoading = true
      const params = {
        ...this.serviceForm,
        displayStart: this.currentPage,
        displayLength: this.pageSize,
        startBindDate: this.serviceForm.createTime
          ? new Date(
            this.serviceForm.createTime[0] + ' ' + '00:00:00'
          ).getTime()
          : '',
        endBindDate: this.serviceForm.createTime
          ? new Date(
            this.serviceForm.createTime[1] + ' ' + '23:59:59'
          ).getTime()
          : ''
      }
      getEquityList(params).then((res) => {
        this.listLoading = false
        if (res) {
          if (Number(res.code) === 1) {
            const obj = res.obj
            this.tableData = obj.data || []
            this.total = obj.total
          } else if (Number(res.code) === 0) {
            this.$confirm(res.msg, {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          } else {
            this.$confirm(this.$t(res.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        }
      })
    },

    // 冻结/解冻确定
    freezeSubmit (type) {
      if (!this.freezeShowBtn) {
        this.isFreezeDialog = false
        return false
      } else {
        if (type === '冻结') {
          this.paramsFrozenState = '2'
        } else {
          this.paramsFrozenState = '1'
        }
        this.listLoading = true
        const params = {
          frozenState: this.paramsFrozenState,
          frozenIdList: this.frozenIdList
        }
        freezeStatus(params).then((res) => {
          this.listLoading = false
          if (res) {
            if (Number(res.code) === 1) {
              this.isFreezeDialog = false
              this.$confirm(type + '成功', {
                confirmButtonText: '确定',
                showCancelButton: false
              }).then(() => {
                this.fetchList()
              })
            } else {
              this.isFreezeDialog = false
              this.$confirm(res.code, {
                confirmButtonText: '确定',
                showCancelButton: false
              })
            }
          }
        })
      }
    },

    resetForm (formName) {
      this.serviceForm = {
        code: '',
        name: '',
        isBoundCoupon: '',
        status: '',
        createTime: [],
        serviceProviderName: '',
        displayStart: 0, // 开始查询条数
        displayLength: 10 // 每页展示条数
      }
      this.searchService()
    },
    pageSizeChange (size) {
      this.pageSize = size
      this.fetchList()
    },
    currentPageChange (curPage) {
      this.currentPage = curPage - 1
      this.fetchList()
    },
    handleSelectionChange (val) {
      this.frozenIdList = []
      this.selectData = val
      this.selectData.forEach(e => {
        this.frozenIdList.push(e.id)
      })
      if (this.selectData.length > 0) {
        this.freezeAbled = false
      } else {
        this.freezeAbled = true
      }
    },
    // 冻结按钮
    freeze (e) {
      this.freezeShowBtn = true
      if (this.selectData.every(e => {
        return e.frozenState === '1'
      })) {
        this.freezeContent = '是否冻结所选服务包'
      } else {
        this.freezeShowBtn = false
        this.freezeContent = '所选服务包包含冻结，请重新选择'
      }
      this.freezeTitle = e
      this.isFreezeDialog = true
    },

    // 解冻按钮
    unfreeze (e) {
      this.freezeShowBtn = true
      if (this.selectData.every(e => {
        return e.frozenState === '2'
      })) {
        this.freezeContent = '是否解冻所选服务包'
      } else {
        this.freezeShowBtn = false
        this.freezeContent = '所选服务包包含正常，请重新选择'
      }
      this.freezeTitle = e
      this.isFreezeDialog = true
    },

    Disable (row) {
      if (
        !this.$auth(
          'serviceRightsConfigurationCenter:serviceManagement:changeStatus'
        )
      ) {
        this.$alert('您没有权限')
        return false
      }

      let statusFlag
      if (row.status === '1' || row.status === '3') {
        statusFlag = true
      } else {
        statusFlag = false
      }
      const params = {
        id: row.id,
        status: row.status === '3' ? '2' : '3'
      }
      this.$alert(
        `是否${statusFlag ? '启用' : '禁用'}此服务`,
        `${statusFlag ? '启用' : '禁用'}`,
        {
          showCancelButton: true,
          showConfirmButton: true,
          callback: (action) => {
            if (action === 'confirm') {
              saveServiceEdit(params).then((res) => {
                if (res) {
                  if (Number(res.code) === 1) {
                    this.$alert('操作成功')
                    this.fetchList()
                  } else if (Number(res.code) === 0) {
                    this.$alert('操作失败')
                  }
                }
              })
            }
          }
        }
      )
    },
    toPreview (row) {
      if (
        !this.$auth('serviceRightsConfigurationCenter:serviceRightsManagement:detail')
      ) {
        this.$alert('您没有权限')
        return false
      }
      this.$router.push({ name: 'equityDetails', params: { id: row } })
    },
    addservice () {
      // if (!this.$auth('serviceRightsConfigurationCenter:serviceManagement:add')) {
      //   this.$alert('您没有权限')
      //   return false
      // }
      this.$router.push({ name: 'addService', id: '' })
    },
    editservice (row) {
      if (
        !this.$auth('serviceRightsConfigurationCenter:serviceManagement:edit')
      ) {
        this.$alert('您没有权限')
        return false
      }
      this.$router.push({ name: 'editService', params: { id: row.id } })
    },
    closeFilter () {
      this.showContent = !this.showContent
    }
  }
}
</script>

<style lang="scss" scoped>
.freeze-footer {
  float: right;
  margin-top: 10px;
}
</style>
